package com.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sys.Constants;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.os.Environment;
import android.text.TextUtils;

@SuppressLint("SimpleDateFormat")
public class Utils {
	public static final String PACKAGE_NAME = "com.hunantv.imgo.guizhou";// package
																			// name

	public static String getClientVersionHead(Context context) {

		String pName = "com.hunantv.imgo.activity";
		String versionName = getVersionName(context);
		return "Android|" + versionName;
	}

	public static String getVersionName(Context context) {
		String versionName = "1.0";
		try {
			PackageInfo pinfo = context.getPackageManager().getPackageInfo(
					PACKAGE_NAME, PackageManager.GET_CONFIGURATIONS);
			versionName = pinfo.versionName;
		} catch (NameNotFoundException e) {

		}

		return versionName;
	}
	
	public static int getVersionCode(Context context) {

		int versionCode = 8;
		try {
			PackageInfo pinfo = context.getPackageManager().getPackageInfo(
					PACKAGE_NAME, PackageManager.GET_CONFIGURATIONS);
			versionCode = pinfo.versionCode;
		} catch (NameNotFoundException e) {

		}

		return versionCode;
	}

	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
		// 鏃嬭浆鍥剧墖 鍔ㄤ綔
		Matrix matrix = new Matrix();
		;
		matrix.postRotate(angle);
		System.out.println("angle2=" + angle);
		// 鍒涘缓鏂扮殑鍥剧墖
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
				bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		return resizedBitmap;
	}

	public static Bitmap getImageThumbnail(String imagePath,int width,int height) {
		Bitmap bitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inPreferredConfig = Bitmap.Config.RGB_565;
		options.inPurgeable = true;
		options.inInputShareable = true;
		options.inJustDecodeBounds = true;
		// 鑾峰彇杩欎釜鍥剧墖鐨勫鍜岄珮锛屾敞鎰忔澶勭殑bitmap涓簄ull
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		options.inJustDecodeBounds = false; // 璁句负 false
		// 璁＄畻缂╂斁姣�
		int h = options.outHeight;
		int w = options.outWidth;
		int beWidth = w / width;
		int beHeight = h / height;
		int be = 1;
		if (beWidth < beHeight) {
			be = beWidth;
		} else {
			be = beHeight;
		}
		if (be <= 0) {
			be = 1;
		}
		options.inSampleSize = be;
		// 閲嶆柊璇诲叆鍥剧墖锛岃鍙栫缉鏀惧悗鐨刡itmap锛屾敞鎰忚繖娆¤鎶妎ptions.inJustDecodeBounds 璁句负 false
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		// 鍒╃敤ThumbnailUtils鏉ュ垱寤虹缉鐣ュ浘锛岃繖閲岃鎸囧畾瑕佺缉鏀惧摢涓狟itmap瀵硅薄

		h = bitmap.getHeight();
		w = bitmap.getWidth();

		if (h < height && w < width)
			return bitmap;
		if (w > width) {
			height = width * h / w;
		} else {
			width = height * w / h;
		}

		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
				ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		return bitmap;
	}

	public static Bitmap getImageThumbnailIcon(InputStream stream, int width, int height) {
		Bitmap bitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inPreferredConfig = Bitmap.Config.ARGB_4444;
		options.inPurgeable = true;
		options.inInputShareable = true;
		options.inJustDecodeBounds = true;

		bitmap = BitmapFactory.decodeStream(stream, null, options);
		options.inJustDecodeBounds = false; // 璁句负 false

		int h = options.outHeight;
		int w = options.outWidth;
		int beWidth = w / width;
		int beHeight = h / height;
		int be = 1;
		if (beWidth < beHeight) {
			be = beWidth;
		} else {
			be = beHeight;
		}
		if (be <= 0) {
			be = 1;
		}
		options.inSampleSize = be;

		bitmap = BitmapFactory.decodeStream(stream, null, options);
		return bitmap;
	}
	
	public static String readFromFile(Context context) {
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			String foldername = Environment.getExternalStorageDirectory()
					.getPath() + "/data";
			File folder = new File(foldername);

			if (folder == null || !folder.exists()) {
				folder.mkdir();
			}

			String fileName = "/syslz" + ".ini";
			File targetFile = new File(foldername + fileName);
			String readedStr = "";

			try {
				if (!targetFile.exists()) {
					targetFile.createNewFile();
					return "error";
				} else {
					InputStream in = new BufferedInputStream(
							new FileInputStream(targetFile));
					BufferedReader br = new BufferedReader(
							new InputStreamReader(in, "UTF-8"));
					String tmp;

					while ((tmp = br.readLine()) != null) {
						readedStr += tmp;
					}
					br.close();
					in.close();

					return readedStr;
				}
			} catch (Exception e) {
				return e.toString();
			}
		} else {
			return "error";
		}
	}

	public static String SavedToText(Context context, String stringToWrite) {
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			String foldername = Environment.getExternalStorageDirectory()
					.getPath() + "/data";
			File folder = new File(foldername);

			if (folder == null || !folder.exists()) {
				folder.mkdir();
			}

			String fileName = "/syslz" + ".ini";
			File targetFile = new File(foldername + fileName);
			OutputStreamWriter osw;

			try {
				if (!targetFile.exists()) {
					targetFile.createNewFile();
					osw = new OutputStreamWriter(new FileOutputStream(
							targetFile), "utf-8");
					osw.write(stringToWrite);
					osw.close();
				} else {
					osw = new OutputStreamWriter(new FileOutputStream(
							targetFile, false), "utf-8");
					osw.write(stringToWrite);
					osw.flush();
					osw.close();
				}
			} catch (Exception e) {
			}
		} else {
			return "error";
		}

		return "";
	}

	public static String ConverToString(Date date, String format) {
		DateFormat df = new SimpleDateFormat(format);
		return df.format(date);
	}

	public static Date ConverToDate(String strDate, String format) {
		if(strDate != null)
		{
			DateFormat df = new SimpleDateFormat(format);
			try {
				return df.parse(strDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}

		return new Date();
	}

	static public String formatDate(String str, String format) {
		Date date = ConverToDate(str, format);
		return ConverToString(date, format);
	}

	public static Bitmap small(Bitmap bitmap, int angle) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();

		float scale = 0;
		if (width > 600)
			scale = (float) (600.0 / width);
		else if (height > 800)
			scale = (float) (800.0 / height);
		else
			return bitmap;

		Matrix matrix = new Matrix();
		matrix.postScale(scale, scale); // 闀垮拰瀹芥斁澶х缉灏忕殑姣斾緥
		if (angle > 0)
			matrix.setRotate(angle);
		Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
				bitmap.getHeight(), matrix, true);
		return resizeBmp;
	}

	public static Bitmap scalePic(Bitmap bitmap, int newWidth, int newHeight) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		// create the new Bitmap object
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		return resizedBitmap;
	}

	public static String Md5(String plainText) {
		StringBuffer buf = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();
			int i;
			buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return buf.toString().toLowerCase();
	}
	
	public static boolean isEmail(String strEmail) {
		String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        return strEmail.matches(regex);
	} 
	
	public static boolean isMobileNO(String mobiles) {  
		String telRegex = "[1][34578]\\d{9}";
	    if (TextUtils.isEmpty(mobiles)) return false;  
	    else return mobiles.matches(telRegex); 
    } 
	
	public static String getDateStr(String date)
	{
		Date now = new Date();
		Date com = ConverToDate(date, "yyyy-MM-dd HH:mm:ss");
		
		int day = (int) ((now.getTime()/1000 - com.getTime()/1000)/(24*3600));
		
		if(day == 0) return ConverToString(com, "HH:mm");
		else if(day < 30) return day + "天前";
		return "30天前";
	}
	
	public static Bitmap createScaleBitmap(Bitmap src, int dstWidth,
            int dstHeight) {
        Bitmap dst = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, false);
        if (src != dst) { // 如果没有缩放，那么不回收
            src.recycle(); // 释放Bitmap的native像素数组
        }
        return dst;
    }
	
	public static void write2File(InputStream is)
	{
		try {
			File mPhotoFile = new File(Constants.PIC_PATH_TMP);// 将要保存图片的路径
			mPhotoFile.deleteOnExit();
			
			FileOutputStream fos = new FileOutputStream(Constants.PIC_PATH_TMP);
			byte[] b = new byte[1024];
			while((is.read(b)) != -1){
				fos.write(b);
			}
			is.close();
			fos.close();
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}
